<template>
  <div class="login-container">
    <!-- 背景装饰元素 -->
    <div class="decorator-circle circle-1"></div>
    <div class="decorator-circle circle-2"></div>
    <div class="decorator-circle circle-3"></div>

    <!-- 登录卡片 -->
    <div class="login-card" v-if="isLogin">
      <!-- 顶部logo和标题 -->
      <div class="login-header">
        <el-icon :size="80">
          <component is="IconLogo"></component>
        </el-icon>
        <h1>图书管理系统</h1>
        <p class="subtitle">欢迎回来，请登录您的账户</p>
      </div>
      <!-- 登录表单 -->
      <el-form :model="loginForm" ref="loginFormRef" :rules="rules" class="login-form">
        <el-form-item prop="userName">
          <el-input
              placeholder="用户名"
              prefix-icon="User"
              v-model="loginForm.userName"
              size="large"
              class="custom-input"
          ></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              placeholder="密码"
              type="password"
              prefix-icon="Lock"
              v-model="loginForm.password"
              size="large"
              show-password
              class="custom-input"
          ></el-input>
        </el-form-item>

        <el-form-item prop="captchaValue" class="captcha-item">
          <el-input
              v-model="loginForm.captchaValue"
              placeholder="验证码"
              prefix-icon="Key"
              size="large"
              class="custom-input captcha-input"
          ></el-input>
          <div class="captcha-image" @click="getCapechaImageUrl">
            <img :src="captchaImageUrl" alt="验证码" v-if="captchaImageUrl">
            <div class="captcha-placeholder" v-else>
              <i class="el-icon-refresh"></i>
            </div>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              size="large"
              @click="login(loginFormRef)"
              class="login-btn"
              :loading="loginLoading"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 底部链接 -->
      <div class="login-footer">
        <el-link type="info">忘记密码?</el-link>
        <el-divider direction="vertical"></el-divider>
        <el-link type="primary" @click="switchToRegister">注册新账户</el-link>
      </div>
    </div>

    <!-- 注册卡片 -->
    <div class="login-card" v-else>
      <!-- 顶部logo和标题 -->
      <div class="login-header">
        <el-icon :size="80">
          <component is="IconLogo"></component>
        </el-icon>
        <h1>用户注册</h1>
        <p class="subtitle">创建您的图书管理系统账户</p>
      </div>

      <!-- 注册表单 -->
      <el-form :model="registerForm" ref="registerFormRef" :rules="registerRules" class="login-form">
        <el-form-item prop="username">
          <el-input
              placeholder="用户名"
              prefix-icon="User"
              v-model="registerForm.username"
              size="large"
              class="custom-input"
          ></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              placeholder="密码"
              type="password"
              prefix-icon="Lock"
              v-model="registerForm.password"
              size="large"
              show-password
              class="custom-input"
          ></el-input>
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
              placeholder="确认密码"
              type="password"
              prefix-icon="Lock"
              v-model="registerForm.confirmPassword"
              size="large"
              show-password
              class="custom-input"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              size="large"
              @click="handleRegister(registerFormRef)"
              class="login-btn"
              :loading="registerLoading"
          >
            注册
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 底部链接 -->
      <div class="login-footer">
        <span>已有账户?</span>
        <el-link type="primary" @click="switchToLogin">立即登录</el-link>
      </div>
    </div>

    <!-- 版权信息 -->
    <div class="copyright">
      © 图书管理系统 | 版本 1.0.0
      <br>重庆外语外事学院 软件工程3班
    </div>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import {useUserStore} from '@/stores/user'
import {reqGetCaptcha,} from "@/api/index.js";
import {ElMessage} from "element-plus";
import { reqUserRegister} from "@/api/system/user.js";

const userStore = useUserStore()
let isLogin = ref(true) // 控制登录/注册表单切换

// 登录相关
let loginFormRef = ref()
let loginForm = reactive({
  userName: 'admin',
  password: '123456',
  captchaValue: '',
  captchaKey: ''
})
let loginLoading = ref(false)
let captchaImageUrl = ref('')

// 注册相关
let registerFormRef = ref()
let registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: ''
})
let registerLoading = ref(false)

/**
 * 获取验证码
 * @returns {Promise<void>}
 */
let getCapechaImageUrl = async () => {
  let res = await reqGetCaptcha()
  captchaImageUrl.value = res.data.captchaImage
  loginForm.captchaKey = res.data.captchaKey
  loginForm.captchaValue = ''
}

let login = (r) => {
  r.validate(async valid => {
    if (valid) {
      loginLoading.value = true
      try {
        await userStore.userLogin(loginForm)
      } catch (e) {
      }
      loginLoading.value = false
    }
  })
}

// 切换注册表单
const switchToRegister = () => {
  isLogin.value = false
}

// 切换登录表单
const switchToLogin = () => {
  isLogin.value = true
}

// 处理注册
const handleRegister = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      registerLoading.value = true
      try {
        await reqUserRegister({
          username: registerForm.username,
          password: registerForm.password
        })
        ElMessage.success('注册成功，请登录')
        switchToLogin()
        // 清空注册表单
        registerForm.username = ''
        registerForm.password = ''
        registerForm.confirmPassword = ''
      } finally {
        registerLoading.value = false
      }
    }
  })
}

// 验证确认密码
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

onMounted(() => {
  getCapechaImageUrl()
})

let rules = reactive({
  userName: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
  ],
  captchaValue: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
  ]
})

let registerRules = reactive({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur'},
    {pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: '密码必须包含字母和数字', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请再次输入密码', trigger: 'blur'},
    {validator: validateConfirmPassword, trigger: 'blur'}
  ]
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  background-size: cover;
  position: relative;
  overflow: hidden;
  padding: 20px;
}

.decorator-circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(64, 158, 255, 0.1);
  z-index: 0;
}

.circle-1 {
  width: 300px;
  height: 300px;
  top: -100px;
  left: -100px;
}

.circle-2 {
  width: 200px;
  height: 200px;
  bottom: -50px;
  right: -50px;
}

.circle-3 {
  width: 150px;
  height: 150px;
  top: 50%;
  right: 10%;
}

.login-card {
  width: 100%;
  max-width: 420px;
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
  transition: all 0.3s ease;
}

.login-card:hover {
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  width: 80px;
  height: 80px;
  background: #409EFF;
  border-radius: 50%;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.logo i {
  font-size: 40px;
  color: white;
}

.login-header h1 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 8px;
  font-weight: 600;
}

.subtitle {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.login-form {
  margin-top: 30px;
}

.custom-input {
  border-radius: 8px;
}

.custom-input :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6;
  transition: all 0.3s ease;
}

.custom-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.custom-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409EFF !important;
}

.captcha-item {
  display: flex;
  align-items: center;
}

.captcha-input {
  flex: 1;
  margin-right: 10px;
}

.captcha-image {
  width: 120px;
  height: 40px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  transition: all 0.3s ease;
}

.captcha-image:hover {
  background: #e4e7ed;
}

.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.captcha-placeholder {
  color: #909399;
  font-size: 20px;
}

.login-btn {
  width: 100%;
  border-radius: 8px;
  font-weight: 500;
  letter-spacing: 1px;
  height: 48px;
  margin-top: 10px;
}

.login-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  font-size: 14px;
  gap: 8px;
}

.copyright {
  position: absolute;
  bottom: 20px;
  left: 0;
  right: 0;
  text-align: center;
  color: #909399;
  font-size: 12px;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .login-card {
    padding: 30px 20px;
  }

  .logo {
    width: 60px;
    height: 60px;
  }

  .logo i {
    font-size: 30px;
  }
}
</style>
